import React, { Component, Fragment } from 'react'
import { Alert, Input, Form, Button, Space, Empty, message, Spin } from 'antd'
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons'

import regexp from '@/Utils/regexp'
import request from '@/Utils/fecth'
import { address } from '@/Utils/apiConfig'

const { setting } = address

export default class IpConfig extends Component {
  constructor(props) {
    super(props)
    this.state = {
      loading: false,
      btnLoading: false,
    }
  }

  componentDidMount() {
    this.getBlackList()
  }

  getBlackList = async() => {
    this.setState({
      loading: true,
    })
    const { code, data } = await request().get(setting.getBlackList)
    this.setState({
      loading: false,
    })
    if (code === 200) {
      const blackList = (data || []).reduce((arr, v) => {
        const [start = '', end = ''] = (v || '').split('-');
        (start || end) && arr.push({
          start,
          end,
        })
        return arr
      }, [])
      this.form && this.form.setFieldsValue({
        blackList,
      })
    }
  }

  onFinish = async(values) => {
    let { blackList = [] } = values || {}
    blackList = blackList.filter(v => v.start).map(v => {
      const start = (v.start || '').trim()
      const end = (v.end || '').trim()
      if (start === end) {
        return start
      }
      if (end) {
        return `${start}-${end}`
      }
      return end ? `${start}-${end}` : start
    })
    this.setState({
      btnLoading: true,
    })
    const { code } = await request().post(setting.getBlackList, {
      blackList,
    })
    this.setState({
      btnLoading: false,
    })
    if (code === 200) {
      message.success('保存成功')
      this.getBlackList()
    }
  };

  render() {
    const { loading, btnLoading } = this.state
    return <div className="IpConfig tab-pane-box">
      <Alert
        description="请设置ip段的黑名单，中间以英文字段“-”隔开，示例“220.249.16.230-220.249.16.232”；可折行设置多个ip段黑名单"
        type="success"
        className="mb24"
      />
      <Spin spinning={loading}>
        <Form onFinish={this.onFinish} ref={c => this.form = c} autoComplete="off">
          <Form.List name="blackList">
            {(fields, { add, remove }) => (
              <Fragment>
                {
                  !fields.length &&
                <Empty style={{ width: '420px' }} description="暂未配置黑名单" className="mb24" />
                }
                {fields.map(({ key, name, fieldKey, ...restField }) => {
                  return <Space key={key} style={{ display: 'flex' }} align="baseline">
                    <Form.Item
                      {...restField}
                      name={[name, 'start']}
                      fieldKey={[fieldKey, 'start']}
                      rules={[
                        { required: true, message: '请输入ip地址' },
                        {
                          pattern: regexp.ipaddr,
                          message: '请输入正确的ip地址',
                        },
                      ]}
                    >
                      <Input placeholder="请输入ip地址" autoFocus />
                    </Form.Item>
                    <span>-</span>
                    <Form.Item
                      shouldUpdate
                      noStyle
                    // dependencies={['blackList', fieldKey, 'start']}
                    >
                      {
                        ({ getFieldValue }) => {
                          return <Form.Item
                            {...restField}
                            fieldKey={[fieldKey, 'end']}
                            name={[name, 'end']}
                            rules={[
                              () => {
                                return {
                                  validator(_, value) {
                                    if (!value) {
                                      return Promise.resolve()
                                    }
                                    if (value && !regexp.ipaddr.test(value)) {
                                      return Promise.reject('请输入正确的ip地址')
                                    }
                                    return Promise.resolve()
                                  },
                                }
                              },
                            ]}
                          >
                            <Input
                              disabled={!getFieldValue(['blackList', fieldKey, 'start'])}
                              placeholder="请输入ip地址"
                            />
                          </Form.Item>
                        }
                      }
                    </Form.Item>
                    <MinusCircleOutlined onClick={() => remove(name)} />
                  </Space>
                })}
                <Form.Item>
                  <Button style={{ width: '420px' }} type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                    添加IP
                  </Button>
                </Form.Item>
                <Form.Item>
                  <Button loading={btnLoading} style={{ width: '420px' }} type="primary" htmlType="submit">
                    保存
                  </Button>
                </Form.Item>
              </Fragment>
            )}
          </Form.List>
        </Form>
      </Spin>

    </div>
  }
}
